package cn.stylefeng.guns.modular.api.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.api.entity.Sale;
import cn.stylefeng.guns.modular.api.mapper.SaleMapper;
import cn.stylefeng.guns.modular.api.model.params.SaleParam;
import cn.stylefeng.guns.modular.api.model.result.SaleResult;
import  cn.stylefeng.guns.modular.api.service.SaleService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 销售管理 服务实现类
 * </p>
 *
 * @author wusonghe
 * @since 2019-08-31
 */
@Service
public class SaleServiceImpl extends ServiceImpl<SaleMapper, Sale> implements SaleService {

    @Override
    public void add(SaleParam param){
        Sale entity = getEntity(param);
        Long orderId =new Random().nextLong();
        orderId = Math.abs(orderId);
        entity.setOrderId(orderId);
        this.save(entity);
    }

    @Override
    public void delete(SaleParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(SaleParam param){
        Sale oldEntity = getOldEntity(param);
        Sale newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public SaleResult findBySpec(SaleParam param){
        return null;
    }

    @Override
    public List<SaleResult> findListBySpec(SaleParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(SaleParam param){
        Page pageContext = getPageContext();
        if (pageContext.getSize()==0) {
            List datas =  this.baseMapper.customList(param);
            return LayuiPageFactory.createDataInfo(datas);
        }
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(SaleParam param){
        return param.getSaleId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Sale getOldEntity(SaleParam param) {
        return this.getById(getKey(param));
    }

    private Sale getEntity(SaleParam param) {
        Sale entity = new Sale();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
